package view;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;

import controle.Controle;
import controle.ListenerControle;

public class PanelEditor extends JPanel implements ListenerControle {

	private JTextArea areaTexto;
	private JPanel panelLinhas;
	private Dimension tamanhoLinha;

	public PanelEditor() {
		tamanhoLinha = new Dimension(30, 13);
		Controle.getInstancia().addListener(this);
		setLayout(new BorderLayout());
		addComponentes();
	}

	private void addComponentes() {
		areaTexto = new JTextArea("");
		areaTexto.addKeyListener(new KeyAdapter() {

			@Override
			public void keyReleased(KeyEvent tecla) {
				Controle.getInstancia().setTextoEditor(areaTexto.getText());
				if (areaTexto.getLineCount() >= 50) {
					geraLinhas(areaTexto.getLineCount());
				}
			}
		});

		JPanel panel = new JPanel(new BorderLayout());
		panel.add(getPanelLinhas(), BorderLayout.WEST);
		panel.add(areaTexto, BorderLayout.CENTER);

		JScrollPane scroll = new JScrollPane(panel);
		scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
		scroll.setPreferredSize(new Dimension(700, 300));
		add(scroll);
	}

	private void geraLinhas(int linhaAtualFinal) {
		JLabel label = null;
		for (int i = linhaAtualFinal; i <= areaTexto.getLineCount(); i++) {
			label = new JLabel(Integer.toString(i + 1));
			label.setPreferredSize(tamanhoLinha);
			panelLinhas.add(label);
		}
	}

	private Component getPanelLinhas() {
		panelLinhas = new JPanel();
		panelLinhas.setPreferredSize(new Dimension(30, 300));
		JLabel label = null;
		for (int i = 0; i < 50; i++) {
			label = new JLabel(Integer.toString(i + 1));
			label.setPreferredSize(tamanhoLinha);
			panelLinhas.add(label);
		}
		return panelLinhas;
	}

	public JTextArea getTextAreaEditor() {
		return areaTexto;
	}

	@Override
	public void novo() {
		areaTexto.setText("");
	}

	@Override
	public void abrir(String nomeArq, String texto) {
		areaTexto.setText(texto);
	}

	@Override
	public void copiar() {
		areaTexto.copy();
	}

	@Override
	public void colar() {
		areaTexto.paste();
	}

	@Override
	public void recortar() {
		areaTexto.cut();
	}

	@Override
	public void salvar(String nomeArq) {
	}

	@Override
	public void mudaTexto() {
	}

	@Override
	public void compilar(List<String> lista) {
	  
	}

	@Override
	public void gerarCodigo(String msg) {}
}